#include "Timer.h"
#include <windows.h>

namespace Steak {
namespace util {
#if defined(WIN32) && !defined(NO_HIRES_TIMER)
	struct Timer::Impl {
		LARGE_INTEGER freq;
		LARGE_INTEGER startTicks;
		LARGE_INTEGER endTicks;
		double inv;
	};

	Timer::Timer() {
		impl = (Impl*)&reserved[0];
		QueryPerformanceFrequency( &impl->freq );
		impl->inv = 1. / impl->freq.QuadPart;
	}
	
	void Timer::start() {
		QueryPerformanceCounter( &impl->startTicks );
	}

	void Timer::stop() {
		QueryPerformanceCounter( &impl->endTicks );
	}

	double Timer::poll() const {
		LARGE_INTEGER end;
		QueryPerformanceCounter( &end );
		return (end.QuadPart - impl->startTicks.QuadPart) * impl->inv;
	}

	double Timer::elapsed() const {
		return (impl->endTicks.QuadPart - impl->startTicks.QuadPart) * impl->inv;
	}
	
#else // Fall back to SDL_GetTicks
	struct Timer::Impl {
		unsigned startTicks;
		unsigned endTicks;
	};

	Timer::Timer() {
		impl = (Impl*)&reserved[0];
	}

	void Timer::start() {
		impl->startTicks = SDL_GetTicks();
	}

	void Timer::stop() {
		impl->endTicks = SDL_GetTicks();
	}

	double Timer::elapsed() const {
		return (impl->endTicks - impl->startTicks) / 1000.;
	}

	double Timer::poll() const {
		return (SDL_GetTicks() - impl->startTicks) / 1000.;
	}
#endif
}
}
